package com.cedar.demo.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

import org.springframework.util.ObjectUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;


/**
 * @Description:json解析工具
 * @author:hutao
 * @mail:hutao_2017@aliyun.com
 * @date:2021年3月3日
 */
public class JsonUtils {

	private static String dateFormat = "yyyy-MM-dd HH:mm:ss";
	
	private static String timeZone = "GMT+8";
	
    private static ObjectMapper objectMapper = new ObjectMapper();
    static {
    	objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    	objectMapper.setTimeZone(TimeZone.getTimeZone(timeZone));
    	objectMapper.setDateFormat(new SimpleDateFormat(dateFormat));
    }
    
    
    public static void initFileJson(String filePath,String json) {
		Writer write = null;
		try {
			File file = new File(filePath);
			if(file.exists()) {
				file.delete();
			}
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if(file.createNewFile()) {
				write = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
				write.write(json);
				write.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(write !=null ) {
				try {
					write.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
    
    /**
     * @Description:读取json字符串到java对象中
     * @author hutao
     * @mail hutao_2017@aliyun.com
     * @date 2021年2月24日
     */
    public static <T> T stringToJavaBean(String strJson, Class<T> type){
        try {
			return objectMapper.readValue(strJson, type);
		} catch (Exception e) {
			e.printStackTrace();
		} 
        return null;
    }

    /**
     * @Description:Java对象转Json字符串
     * @author hutao
     * @mail:hutao_2017@aliyun.com
     * @date 2021年2月24日
     */
    public static String javaBeanToString(Object javaBean) {
        if (ObjectUtils.isEmpty(javaBean)) {
            return "";
        }
        try {
			return objectMapper.writeValueAsString(javaBean);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return "";
    }

}
